package cn.jsu.oj.dispatchServer.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 提供手动获取被spring管理的bean对象
 * @author ahtonc
 */
@Component
public class SpringUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        if(applicationContext == null){
            applicationContext = context;
        }
        
    }

    /**
     * @Description:    获取applicationContext
     */
    public static ApplicationContext getApplicationContext(){
        return applicationContext;
    }


    /**
     * @Description:    通过name获取bean
     */
    public static Object getBean(String name){
        try {
            return getApplicationContext().getBean(name);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * @Description:    通过class获取bean
     */
    public static<T>T getBean(Class<T> clazz){
        try {
            return getApplicationContext().getBean(clazz);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * @Description:    通过name,以及clazz返回的指定的Bean
     */
    public static<T> T getBean(String name, Class<T> clazz){
        try {
            return getApplicationContext().getBean(name, clazz);
        } catch (Exception e) {
            return null;
        }
    }

}

